package me.ywd.ribbon.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Ye_Wenda
 * @Date 9/15/2017
 */
@RestController
@RequestMapping("/demo")
public class RibbonDemoController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("")
    public String demo() {
        Map<String, String> map = new HashMap<>();
        return restTemplate.exchange("http://provider/demo", HttpMethod.GET, null, String.class, map).getBody();
    }

    @GetMapping("x")
    public String demoX() {
        Map<String, String> map = new HashMap<>();
        return restTemplate.exchange("http://providerx/demo", HttpMethod.GET, null, String.class, map).getBody();
    }

    @GetMapping("load")
    public String loadDemo() {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("provider");
        System.out.println(serviceInstance.getPort());
        return "";
    }

    @GetMapping("load/x")
    public String loadDemoX() {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("providerx");
        System.out.println(serviceInstance.getPort());
        return "x";
    }
}
